import 'package:flutter/material.dart';
import 'dart:ui' as ui;

import 'package:zhibao_flutter/zone.dart';

class MyGradentText extends StatefulWidget {
  final TextStyle style;
  final String data;
  final List<Color>? colors;

  MyGradentText(this.data, {required this.style, this.colors});

  @override
  State<MyGradentText> createState() => _MyGradentTextState();
}

class _MyGradentTextState extends State<MyGradentText> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      setState(() {});
    });
  }

  Size boundingTextSize({int maxLines = 1, double maxWidth = double.infinity}) {
    if (widget.data.isEmpty) {
      return Size.zero;
    }
    final TextPainter textPainter = TextPainter(
        textDirection: TextDirection.ltr,
        text: TextSpan(text: widget.data, style: widget.style),
        maxLines: maxLines)
      ..layout(maxWidth: maxWidth);

    // print(
    //     "[MyGradentText] [boundingTextSize] data::${widget.data},,size::${textPainter.size.width}");
    // print('');

    return textPainter.size;
  }

  @override
  Widget build(BuildContext context) {
    RenderBox? renderBox = context.findRenderObject() as RenderBox?;
    if (renderBox == null) return Text(widget.data, style: widget.style);
    Offset offset = renderBox.localToGlobal(Offset.zero);
    final afterSub = offset.dx - (boundingTextSize().width / 2);
    // print(
    //     "[MyGradentText] data::${widget.data},,offset::${offset.dx},afterSub:$afterSub");

    final secondValue = afterSub + 30.px;
    return Text(
      widget.data,
      style: widget.style.copyWith(
        foreground: Paint()
          ..shader = ui.Gradient.linear(
            widget.colors == null
                ? Offset(secondValue + 90.px, secondValue + 30.px)
                : Offset(secondValue + 160.px, secondValue + 30.px),
            widget.colors == null
                ? Offset(afterSub, secondValue)
                : Offset(afterSub - 0.px, secondValue),
            widget.colors ?? MyTheme.mainGradientColor(),
          ),
      ),
      textAlign: TextAlign.center,
    );
  }
}
